﻿namespace com.net.wifi_pvp
{
    using com.game.consts;
    using System;
    using System.Net;
    using System.Net.NetworkInformation;
    using System.Runtime.InteropServices;
    using TNet;

    public class LobbyServerItem
    {
        public string accountName;
        public IPEndPoint IPEP;
        public bool isAvailable;
        public int level;
        public int onFightGeneralId;
        public string originalHostname;
        public WifiPvpConst.Signal signal;

        public LobbyServerItem(string hostname, string accName, int onFightGeneralId, int lvl, bool isAvailable, IPEndPoint ipep, WifiPvpConst.Signal signal = 0x7f)
        {
            this.originalHostname = hostname;
            this.accountName = accName;
            this.level = lvl;
            this.isAvailable = isAvailable;
            this.IPEP = ipep;
            this.onFightGeneralId = onFightGeneralId;
            if (signal == WifiPvpConst.Signal.unset)
            {
                PingReply reply = new Ping().Send(ipep.Address);
                if (reply == null)
                {
                    this.signal = WifiPvpConst.Signal.none;
                }
                else if (reply.RoundtripTime < 0x19L)
                {
                    this.signal = WifiPvpConst.Signal.good;
                }
                else if (reply.RoundtripTime < 50L)
                {
                    this.signal = WifiPvpConst.Signal.acceptable;
                }
                else if (reply.RoundtripTime < 200L)
                {
                    this.signal = WifiPvpConst.Signal.weak;
                }
                else
                {
                    this.signal = WifiPvpConst.Signal.none;
                }
            }
            else
            {
                this.signal = signal;
            }
        }

        public static LobbyServerItem GetLobbyServerItem(ServerList.Entry entry)
        {
            return ParseHostName(entry.name, entry.internalAddress);
        }

        private static LobbyServerItem ParseHostName(string hostname, IPEndPoint ipep)
        {
            PVPAccountBrief accountBriefFromHostString = WifiLAN.GetAccountBriefFromHostString(hostname);
            return new LobbyServerItem(hostname, accountBriefFromHostString.accountName, int.Parse(accountBriefFromHostString.onFightGeneralId), int.Parse(accountBriefFromHostString.accountLevel), accountBriefFromHostString.isAvailable, ipep, WifiPvpConst.Signal.none);
        }
    }
}

